package com.yjhb.android.sbz.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.cardview.widget.CardView;

import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.publishtask.PublishActivity;
import com.yjhb.android.sbz.dialog.InputDialog;
import com.yjhb.android.sbz.dialog.MainPageToppingDialog;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.entity.ManagerTask;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.enums.TaskState;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.managercenter.ManagerCenterPresenter;
import com.yjhb.android.sbz.mvp.managercenter.ManagerCenterView;
import com.yjhb.android.sbz.tool.CommonDialogCollect;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.base.BaseDialog;
import com.jojo.android.zxlib.tool.ZxClipboardTool;
import com.jojo.android.zxlib.tool.ZxSpanTool;
import com.jojo.android.zxlib.tool.ZxTimeTool;
import com.jojo.android.zxlib.tool.ZxToast;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2020/12/10 9:35
 */
public class ManagerCenterActivity extends BaseActivity<ManagerCenterPresenter> implements ManagerCenterView {
    private final String TAG = "ManagerCenterActivity";
    @BindView(R.id.spread_title)
    TextView spreadTitle;
    @BindView(R.id.spread_layout)
    CardView spreadLayout;

    private ManagerTask managerTask;
    private Integer state;
    private Integer taskId;

    @BindView(R.id.task_name)
    TextView task_name;
    @BindView(R.id.task_state)
    TextView task_state;
    @BindView(R.id.task_id)
    TextView task_id;
    @BindView(R.id.task_price)
    TextView task_price;
    @BindView(R.id.task_total_num)
    TextView task_total_num;
    @BindView(R.id.task_current_num)
    TextView task_current_num;
    @BindView(R.id.task_publish_time)
    TextView task_publish_time;
    @BindView(R.id.watch_tv)
    TextView watch_tv;
    @BindView(R.id.doing_tv)
    TextView doing_tv;
    @BindView(R.id.pass_tv)
    TextView pass_tv;
    @BindView(R.id.fail_tv)
    TextView fail_tv;
    @BindView(R.id.check_tv)
    TextView check_tv;
    //    @BindView(R.id.quick_trial_tv)
//    TextView quick_trial_tv;
    @BindView(R.id.content_layout)
    View content_layout;

    boolean isStop = true;

    @Override
    protected ManagerCenterPresenter initPresenter() {
        return new ManagerCenterPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_manager_center;
    }

    @Override
    protected void initUI() {
        content_layout.setVisibility(View.GONE);
        state = getIntent().getIntExtra("state", -1);
        taskId = getIntent().getIntExtra("taskId", -1);
        if (state == -1 || taskId == -1) {
            ZxToast.showFAILBottomToast("没有找到该任务！请刷新后重试！");
            finish();
        }
    }

    @Override
    protected void initData() {
        presenter.loadTask(taskId);
    }

    @Override
    protected void regEvent() {

    }


    @Override
    public void refresh() {
        if (managerTask != null) {
            Task task = managerTask.getTask();
            task_name.setText(task.getName());
            task_state.setText(TaskState.getState(task.getState()).getStateStr());
            switch (TaskState.getState(task.getState())) {
                case TASK_STATE_VIOLATION:
                case TASK_STATE_OFF:
                    spreadLayout.setVisibility(View.GONE);
                    spreadTitle.setVisibility(View.GONE);
                    break;
                default:
                    spreadLayout.setVisibility(View.VISIBLE);
                    spreadTitle.setVisibility(View.VISIBLE);
            }
            task_id.setText("悬赏ID:" + task.getId());
            task_price.setText("悬赏单价:" + task.getMoney() + "元");
            task_total_num.setText("总名额:" + task.getMaxStock() + "个");
            task_current_num.setText("剩余名额:" + task.getCurrentStock() + "个");
            task_publish_time.setText("发布时间:" + ZxTimeTool.date2String(managerTask.getTask().getCreateTime()));
            watch_tv.setText("" + managerTask.getQueryCount());
            doing_tv.setText("" + managerTask.getRunningCount());
            pass_tv.setText("" + task.getSuccess());
            fail_tv.setText("" + task.getFail());
            CharSequence check = "任务审核(待审核" + managerTask.getWaitAuditCount() + ")/已审核";
            if (managerTask.getWaitAuditCount() > 0) {
                check = ZxSpanTool.ColorSpan(check, 8,
                        8 + ("" + managerTask.getWaitAuditCount()).length(), getResources().getColor(R.color.white));
            }
            check_tv.setText(check);
        }
    }

    @Override
    public void onEventMsg(EventMsg msg) {
        super.onEventMsg(msg);
        if (msg.msg == EventMsg.TASK_PUBLISH_SUCCESS) {
            finish();
        }
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @OnClick(R.id.task_detail)
    void task_detail() {
        presenter.getDetails(taskId + "", 2);
    }

    @OnClick(R.id.running_ll)
    void running_ll() {
        Intent intent = new Intent(this, RunningTaskUserListActivity.class);
        intent.putExtra("taskManager", managerTask);
        startActivity(intent);
    }

    /**
     * 暂停
     */
//    @OnClick(R.id.suspend)
    void suspend() {
        final TipsDialog tipsDialog = new TipsDialog(this);
        tipsDialog.setTitle("提示");
        if (managerTask.getTask().getState() != TaskState.TASK_STATE_STOP.getState())
            tipsDialog.setContent("任务暂停后将不再对外展示。\n请确定是否暂停？");
        else
            tipsDialog.setContent("任务恢复后将对外展示。\n请确定是否恢复？");
        tipsDialog.setContentGravity(Gravity.CENTER);
        tipsDialog.setSubmitText("确定" + (isStop ? "暂停" : "恢复"));
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                if (type == TipsDialog.TYPE_SUBMIT) {
                    presenter.stopOrRestartTask(managerTask.getTask().getId() + "", isStop);
                }
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }

    /**
     * 增加悬赏金额
     */
//    @OnClick(R.id.addMoney)
    void addMoney() {
        final InputDialog inputDialog = CommonDialogCollect.addMoney(this);
        inputDialog.setOnClickListener(new InputDialog.OnClickListener() {
            @Override
            public void onClick(int button) {
                if (button == InputDialog.BUTTON_CANCEL) {
                    inputDialog.dismiss();
                } else if (button == InputDialog.BUTTON_SUBMIT) {
                    EditText editText = inputDialog.getInputView();
                    if (Tool.isEditEmpty(editText)) {
                        ZxToast.showBottomToastLight("请输入金额");
                        return;
                    }
                    BigDecimal money = new BigDecimal(editText.getText().toString());
                    if (money.floatValue() < 0.2f) {
                        ZxToast.showINFOBottomToast("请至少提高0.2元");
                        return;
                    }
                    presenter.addMoney(taskId + "", money);
                    inputDialog.dismiss();
                }
            }
        });
        inputDialog.show();
    }


    /**
     * 增加悬赏人数
     */
//    @OnClick({R.id.addNum})
    void addNum() {

        final InputDialog inputDialog = CommonDialogCollect.addNum(this);
        inputDialog.setOnClickListener(new InputDialog.OnClickListener() {
            @Override
            public void onClick(int button) {
                if (button == InputDialog.BUTTON_CANCEL) {
                    inputDialog.dismiss();
                } else if (button == InputDialog.BUTTON_SUBMIT) {
                    EditText editText = inputDialog.getInputView();
                    if (Tool.isEditEmpty(editText)) {
                        ZxToast.showBottomToastLight("请输入数量");
                        return;
                    }
                    int count = Integer.parseInt(editText.getText().toString());
                    if (count < 5) {
                        ZxToast.showINFOBottomToast("请至少增加5个名额");
                        return;
                    }
                    presenter.addTaskCount(taskId + "", count);
                    inputDialog.dismiss();
                }
            }
        });
        inputDialog.show();
    }

    /**
     * 修改任务
     */
    @OnClick(R.id.modifyTask)
    void modifyTask() {
        if (managerTask == null) return;
        //修改任务限制时间
//        if (managerTask.getTask().getUpdateTime() != null) {
//            long currentTime = System.currentTimeMillis();
//            long updateTime = managerTask.getTask().getUpdateTime().getTime();
//            //VIP用户6小时可修改一次，非VIP用户24小时可修改一次
//            if (currentTime - updateTime > (App.userInfo.getVipLevel() > 0 ?
//                    6 * 60 * 60 * 1000 : 24 * 60 * 60 * 1000)) {
//                if (managerTask.getTask().getState() == TaskState.TASK_STATE_STOP.getState()) {
//                    TipsDialog tipsDialog = new TipsDialog(this);
//                    tipsDialog.setContent("1、严禁反复修改，增加审核工作量。\n" +
//                            "2、任务审核完成才可以修改内容。\n" +
//                            "3、普通用户24小时内可修改一次，会员6小时内可修改一次。");
//                    tipsDialog.setTitle("提示");
//                    tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
//                        @Override
//                        public void onClick(int type) {
//                            if (type == TipsDialog.TYPE_SUBMIT) {
//                                presenter.getDetails("" + taskId, 1);
//                            }
//                            tipsDialog.dismiss();
//                        }
//                    });
//                    tipsDialog.show();
//                } else {
//                    Tool.showTips(this, "请先暂停任务后再进行修改操作！");
//                }
//            } else {
//                Tool.showTips(this, "VIP用户6小时可修改一次，非VIP用户24小时可修改一次，您已修改过一次！");
//            }
//        }
        if (managerTask.getTask().getState() == TaskState.TASK_STATE_STOP.getState()) {
            presenter.getDetails("" + taskId, 1);
        } else {
            Tool.showTips(this, "请先暂停任务后再进行修改操作！");
        }

    }

    /**
     * 定时置顶
     */
    @OnClick(R.id.timerTopping)
    void timerTopping() {
        Tool.startAddTimerActivity(this, taskId, 1);
    }

    /**
     * 定时刷新
     */
//    @OnClick(R.id.timerRefresh)
    void timerRefresh() {
        Tool.startAddTimerActivity(this, taskId, 2);
    }

    /**
     * 首页置顶
     */
//    @OnClick(R.id.mainPageTopping)
    void mainPageTopping() {
        final MainPageToppingDialog dialog = new MainPageToppingDialog(this);
        dialog.setOnClickListener(new BaseDialog.OnClickListener() {
            @Override
            public void onClick(Dialog dialog1, int button) {
                dialog.dismiss();
                if (button == BaseDialog.BUTTON_SUBMIT) {
                    Integer hour = dialog.getHour();
                    if (hour == null) {
                        ZxToast.showINFOBottomToast("请输入正确的时间");
                        return;
                    }
                    presenter.showMainPage(taskId + "", hour);
                }
            }
        });
        dialog.show();
    }

    /**
     * 任务刷新
     */
    @OnClick(R.id.refresh_package)
    void taskRefresh() {
        startActivity(new Intent(this, RefreshPackageActivity.class));
    }

    /**
     * 快审
     */
//    @OnClick(R.id.quickTrial)
    void quickTrial() {
        TipsDialog tipsDialog = CommonDialogCollect.quickTrial(this, managerTask);
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
                if (type == TipsDialog.TYPE_SUBMIT) {
                    presenter.fastCheck(taskId + "", managerTask.getTask().getAuditFast() == 0);
                }
            }
        });
        tipsDialog.show();
    }

    /**
     * 下架任务
     */
    @OnClick(R.id.off_the_shelf)
    void off_the_shelf() {
        final TipsDialog tipsDialog = new TipsDialog(this);
        tipsDialog.setTitle("结束任务");
        tipsDialog.setContent("任务将会立即下架，且不可恢复，\n请确认是否结束？");
        tipsDialog.setContentGravity(Gravity.CENTER);
        tipsDialog.setSubmitText("确定下架");
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.dismiss();
                if (type == TipsDialog.TYPE_SUBMIT)
                    presenter.downTask(taskId);
            }
        });
        tipsDialog.show();
    }

    //    @OnClick(R.id.sendRedPack)
    void sendRedPack() {
        Tool.startSendRedPackActivity(this, taskId);
    }

    @OnClick(R.id.PC)
    void PC() {
//        presenter.PC();
        String url = "http://a.shangbangzuan.com:81";
        CharSequence text = "悬赏主电脑端审核后台：\n" + url;
        int index = text.toString().indexOf(url);
        text = ZxSpanTool.ClickSpan(text, index, index + url.length(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tool.startExternalWeb(getActivity(), url);
            }
        });
        TipsDialog tipsDialog = new TipsDialog(this);
        tipsDialog.setContent(text);
        tipsDialog.setCanceledOnTouchOutside(true);
        tipsDialog.setContentGravity(Gravity.CENTER);
        tipsDialog.setTitle("提示");
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setSubmitText("复制链接");
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                ZxClipboardTool.copyText(getActivity(),url);
                ZxToast.showSuccessBottomToast("已复制链接");
            }
        });
        tipsDialog.getContentTextView().setMovementMethod(LinkMovementMethod.getInstance());
        tipsDialog.getContentTextView().setHighlightColor(0);
        tipsDialog.show();
    }

    /**
     * 审核
     */
    @OnClick(R.id.check_tv)
    void check_tv() {
        Tool.startCheckListActivity(this, managerTask);
    }


    @OnClick(R.id.title_right_tv)
    void title_right_tv() {
        Intent intent = new Intent(this, MsgActivity.class);
        intent.putExtra("type", 1);
        intent.putExtra("task", managerTask.getTask());
        startActivity(intent);
    }


    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        ZxToast.showFAILBottomToast(msg);
    }

    @Override
    public void onDownTask() {
        loadingDialog.cancel();
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST_ITEM, null));
        ZxToast.showSuccessBottomToast("任务下架成功");
        finish();
    }

    @Override
    public void onWait(String tips) {
        loadingDialog.show();
        loadingDialog.setTipsText(tips);
    }

    @Override
    public void onSuccess(String tips) {
        loadingDialog.cancel();
        ZxToast.showSuccessBottomToast(tips);
        if (tips.equals(ResManager.getString(R.string.task_tips_stop_success))) {
            isStop = false;
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST, TaskState.TASK_STATE_DISPLAY));
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST, TaskState.TASK_STATE_STOP));
            initData();
        } else if (tips.equals(ResManager.getString(R.string.task_tips_restart_success))) {
            isStop = true;
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST, TaskState.TASK_STATE_DISPLAY));
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST, TaskState.TASK_STATE_STOP));
            initData();
        } else if (tips.equals(ResManager.getString(R.string.task_tips_add_money_success)) ||
                tips.equals(ResManager.getString(R.string.task_tips_add_money_success))) {
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_UPDATE_DATA_TASK_MANAGER_LIST, TaskState.TASK_STATE_DISPLAY));
            initData();
        } else if (tips.equals(ResManager.getString(R.string.task_tips_refresh_task_success))) {
            EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
        } else if (tips.equals(ResManager.getString(R.string.task_tips_fast_check_success))
                || tips.equals(ResManager.getString(R.string.task_tips_fast_colse_success))) {
//            managerTask.getTask().setAuditFast(managerTask.getTask().getAuditFast() == 1 ? 0 : 1);
            initData();
//            refresh();
        }

    }

    @Override
    public void onPC(String result) {
        loadingDialog.cancel();
        String url = "a.shangbangzuan.com:81";
        String code = result;
        CharSequence text = "悬赏主电脑端审核后台：" + url + "\n访问码：" + code;
        int index = text.toString().indexOf(url);
        text = ZxSpanTool.ClickSpan(text, index, index + url.length(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        index = text.toString().indexOf(code);
        text = ZxSpanTool.ColorSpan(text, index, index + code.length(), Color.RED);
        TipsDialog tipsDialog = new TipsDialog(this);
        tipsDialog.setContent(text);
        tipsDialog.setContentGravity(Gravity.CENTER);
        tipsDialog.setTitle("提示");
        tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
        tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
            @Override
            public void onClick(int type) {
                tipsDialog.cancel();
            }
        });
        CharSequence finalText = text;
        tipsDialog.getContentTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZxClipboardTool.copyText(getActivity(), finalText.toString());
                ZxToast.showINFOBottomToast("已复制");
            }
        });
        tipsDialog.show();
    }

    @Override
    public void onTaskLoadSuccess(ManagerTask task) {
        this.managerTask = task;
        loadingDialog.cancel();
        refresh();
        content_layout.setVisibility(View.VISIBLE);
    }

    @Override
    public void onTaskDetail(AddTask taskDetail, int use) {
        loadingDialog.cancel();
        //修改任务
        if (use == 1) {
            Tool.startPublishTaskActivity(this, PublishActivity.MODE_MODIFY, taskDetail);
        } else if (use == 2) {
            Tool.startPreviewTaskDetailActivity(this, taskId);
        }
    }

}
